<template>
    <div class="chat-app">
        <!-- 头部 -->
        <div class="header">
            <div class="header-left">
                <el-select v-model="question" @change="selectClict()">
                    <el-option v-for="item in questionList" :key="item.question" :label="item.question"
                        :value="item.question"></el-option>
                </el-select>
                <el-button type="primary" @click="toQuestion()">问题列表维护</el-button>
            </div>


            <div class="user-info">
                <span v-if="showName">{{ user.name }}</span> 
            </div>
        </div>
        <div class="main-content">
            <div class="sidebar">
                <!-- 假设这里是历史聊天记录的展示区域 -->
                <h2>Chat History</h2>
                <!-- 可以在这里展示历史消息列表等内容 -->
                <div class="new-chat" @click="handleNewChatClick">New Chat</div>
                <div v-for="(historyItem, index) in historyList" :key="index" class="history-item"
                    @click="selectHistory(historyItem)">
                    <div class="history-content">
                        <div class="side-message">{{ truncateText(historyItem.messages, 30) }}</div>
                        <div class="time">
                            {{ new Date(historyItem.updateTime).toLocaleString() }}
                        </div>
                    </div>
                </div>
            </div>
            <div class="chat-container">
                <div class="chat-box">
                    <div v-for="(message, index) in messages" :key="index"
                        :class="{ 'user-message': message.type === 'user', 'bot-message': message.type === 'GPT' }"
                        class="message">
                        <markdown-it-vue-light :content="message.text" />
                        <!-- <el-input class="md-body" :content="message.text" /> -->
                    </div>
                </div>
                <div class="input-box">
                    <el-input v-model="userInput" type="textarea" :autosize="{ minRows: 1, maxRows: 4 }"
                        @keyup.enter="sendMessage" placeholder="Type your message..." />
                    <el-button type="primary" @click="sendMessage">发送</el-button>
                </div>
            </div>
        </div>

        <login :show-login-dialog="showLoginDialog" v-on:login-success="handleLoginSuccess" />
    </div>
</template>
 
<script>
import { getHistory, saveHistory } from "./api/History";
import { getQuestionList } from '@/api/Question';
import MarkdownItVueLight from 'markdown-it-vue/dist/markdown-it-vue-light.umd.min.js'
import 'markdown-it-vue/dist/markdown-it-vue-light.css'
import login from "./components/login.vue";
export default {
    name: "chatGpt",
    data() {
        return {
            messages: [],
            userId: undefined,
            history: {},
            historyList: [],
            cnt: 0,
            userInput: '',
            chatContent: '',
            showLoginDialog: false,
            question: "",
            questionList: "",
            user: {},
            showName:false,
        };
    },
    components: {
        MarkdownItVueLight,
        login
    },
    created() {
        let userId = sessionStorage.getItem("userId");
        this.userId = userId;
        if (userId != "" || userId != undefined) {
            this.user = JSON.parse(sessionStorage.getItem("user"));
            this.getHistorys(userId);
            this.handlSelect(userId);
        }
    },
    methods: {
        checkUser() {
            let userId = sessionStorage.getItem("userId");
            if (userId == undefined || userId == "") {
                this.$message({
                    message: '请先登录！',
                    type: 'warning'
                });
                this.showLoginDialog = true
            } else {
                this.userId = userId;
            }
        },
        handleLoginSuccess() {
            // 登录成功后的处理逻辑
            this.userId = sessionStorage.getItem("userId");
            this.user = JSON.parse(sessionStorage.getItem("user"));
            console.log("user:", this.user);
            // 关闭登录对话框
            this.showLoginDialog = false;
            this.getHistorys(this.userId);
            this.handlSelect(this.userId);
            this.showName = true;
        },
        getHistorys(userId) {
            getHistory(userId).then(res => {
                if (res.data.code == 200) {
                    this.historyList = res.data.data;
                    this.cnt = this.historyList.length;
                    console.log("this.historyList:", this.historyList);
                }
            });
        },
        sendMessage() {
            this.checkUser();
            if (this.userInput.trim() !== '' && this.showLoginDialog == false) {
                this.messages.push({ text: this.userInput, type: 'user' });
                // 创建 XMLHttpRequest 对象
                const xhr = new XMLHttpRequest();
                // 设置请求的 URL
                xhr.open('GET', `http://localhost:8081/Chat?message=${this.userInput}`);
                // 监听 readyStateChange 事件
                xhr.onreadystatechange = () => {
                    // 如果 readyState 是 3，表示正在接收数据
                    let index = this.messages.length;
                    if (xhr.readyState === 3) {
                        // 将数据添加到文本框中
                        this.chatContent = xhr.responseText;
                        if (index % 2 != 0) {
                            this.messages.push({ text: xhr.responseText, type: 'GPT' });
                        } else {
                            this.messages[index - 1] = { text: this.chatContent, type: 'GPT' };
                        }
                    }
                    // 如果 readyState 是 4，表示完成请求
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            // 避免接受过程中缺少字符
                            this.messages.pop();
                            this.messages.push({ text: xhr.responseText, type: 'GPT' });
                        }
                        this.saveHistory();
                    }
                }
                // 设置响应类型为 text/event-stream
                xhr.setRequestHeader('Content-Type', 'text/event-stream');
                xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
                // 发送请求
                xhr.send();

            }
            this.userInput = '';

        },
        saveHistory() {
            this.history.userId = this.userId;
            this.history.cnt = this.cnt;
            this.history.messages = JSON.stringify(this.messages);
            console.log("this.history:", this.history);
            saveHistory(this.history).then(res => {
                if (res.data.code == 200) {
                    console.log("数据实时记录成功！")
                    this.getHistorys(this.userId);
                } else {
                    console.log("数据实时记录失败！")
                }
            })
        },
        selectHistory(historyItem) {
            this.messages = JSON.parse(historyItem.messages);
        },
        handleNewChatClick() {
            this.checkUser();
            console.log("messages:", this.messages);
            if (this.messages.length != 0) {
                this.saveHistory();
            }
            // 处理 "New Chat" 点击事件的逻辑
            this.messages = [];
            this.cnt += 1;
        },
        truncateText(text, maxLength) {
            if (text != undefined) {
                // 将 JSON 字符串解析为 JavaScript 对象
                const jsonData = JSON.parse(text);
                // 获取用户发送的文本
                const userText = jsonData[0].text;
                // 截断文本并添加省略号
                if (userText.length > maxLength) {
                    return userText.slice(0, maxLength) + '...';
                }
                return userText;
            }
        },
        toQuestion() {
            this.$router.push({ path: '/question' })
        },
        handlSelect(userId) {
            getQuestionList(userId).then(res => {
                if (res.data.code == 200) {
                    this.questionList = res.data.data;
                }
            });
        },
        selectClict() {
            this.userInput = this.question;
        },
    },
};
</script>
  
<style scoped>
body {
    margin: 0;
    font-family: Arial, sans-serif;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    background-color: #409eff;
    color: #fff;
}

.header-left {
    display: flex;
    align-items: center;
}

.chat-app {
    display: flex;
    flex-direction: column;
    height: 90vh;
}

.time {
    color: #888;
    font-size: 12px;
}

.sidebar {
    flex: 1;
    background-color: #f4f4f4;
    padding: 20px;
    border-right: 1px solid #ccc;
    overflow-y: scroll;
}

.chat-container {
    flex: 3;
    display: flex;
    flex-direction: column;
}

.chat-box {
    flex: 1;
    overflow-y: scroll;
    padding: 10px;
}

.message {
    background-color: #e0f7fa;
    padding: 8px;
    margin-bottom: 8px;
    border-radius: 5px;
}

.user-message {
    text-align: right;
}

.bot-message {
    text-align: left;
}

.input-box {
    display: flex;
    padding: 10px;
    background-color: #fff;
}

.user-input {
    flex: 1;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

button {
    margin-left: 8px;
    padding: 8px;
    background-color: #4caf50;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: #45a049;
}

.text {
    font-size: 14px;
    text-align: left;
}

.item {
    margin-bottom: 18px;
    text-align: left;
}

.history-item {
    display: flex;
    cursor: pointer;
    text-align: left;
    /* 设置文本左对齐 */
    padding: 10px;
    border-bottom: 1px solid #ddd;
}

.history-content {
    flex: 1;
}

.main-content {
    display: flex;
    flex: 1;
}

.side-message {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    color: #555;
}


::-webkit-scrollbar-track {
    background-color: #f4f4f4;
}

/* 滚动条样式 */
::-webkit-scrollbar {
    width: 6px;
}

::-webkit-scrollbar-thumb {
    background-color: #ccc;
    border-radius: 4px;
}

.new-chat {
    cursor: pointer;
    padding: 10px;
    background-color: #4CAF50;
    /* 绿色，可以根据需要调整颜色 */
    color: white;
    text-align: center;
    font-weight: bold;
    margin-bottom: 10px;
}

.user-info {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
}
</style>
  